<template>

  <div class="divBox">


    <el-card class="box-card">
      <div slot="header" class="clearfix">

        <div class="container">
          <div class="demo-input-suffix acea-row">
            <el-form inline size="small" label-width="100px" :model="productFrom" ref="productFrom">
              <el-row>
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                  <el-col>
                    <el-form-item label="京东类目：" prop="cate_ids">
                      <el-cascader v-model="productFrom.cate_ids" :props="cascaderProps" class="selWidth"
                                   @change="getProductJdListApi(true)"/>
                    </el-form-item>
                  </el-col>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                  <el-col>
                    <el-form-item label="选品ID：" prop="cate_id">
                      <el-input v-model="productFrom.cate_id" placeholder="请输入选品ID" clearable class="selWidth"/>
                    </el-form-item>
                  </el-col>
                </el-col>
                <!--                <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">-->
                <!--                  <el-col>-->
                <!--                    <el-form-item label="价格区间开始：" prop="price_start">-->
                <!--                      <el-input v-model="productFrom.price_start" placeholder="请输入价格区间开始" clearable-->
                <!--                                type="number"-->
                <!--                                class="selWidth"/>-->
                <!--                    </el-form-item>-->
                <!--                    <el-form-item label="价格区间结束：" prop="price_end">-->
                <!--                      <el-input v-model="productFrom.price_end" placeholder="请输入价格区间结束" clearable type="number"-->
                <!--                                class="selWidth"/>-->
                <!--                    </el-form-item>-->
                <!--                  </el-col>-->
                <!--                </el-col>-->
                <el-form-item label="关键词：" prop="keyword">
                  <el-input v-model="productFrom.keyword" @keyup.enter.native="getProductJdListApi(true)"
                            placeholder="请输入关键词" class="selWidth" clearable>
                    <el-button slot="append" icon="el-icon-search" class="el-button-solt"
                               @click="getProductJdListApi(true)"/>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-button size="mini" @click="batch(productList) ">批量采集</el-button>
                  <el-button size="mini" @click="reset('productFrom')">重置</el-button>
                </el-form-item>
              </el-row>

            </el-form>
          </div>
        </div>

      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="productList"
        style="width: 100%"
        border
        size="small"
        @selection-change="handleSelectionChange"
        row-key="store_category_id"
        :default-expand-all="false"
      >
        <el-table-column key="2" type="selection" width="55" :selectable="checkboxSelect" fixed="left"/>
        <el-table-column
          align="center"
          label="序号"
          min-width="40"
          prop="title"
        >
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="京东SKU编号"
          min-width="120"
          prop="skuId"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.skuId }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="sku价格"
          sortable
          min-width="110"
          prop="skuPrice"
          :sort-method="(a,b)=>{return a.skuPrice - b.skuPrice}"
        >
          <template slot-scope="scope">
            <span style="color:#f00;font-weight: bold">{{ scope.row.skuPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="市场价"
          sortable
          min-width="110"
          prop="backStagePrice"
          :sort-method="(a,b)=>{return a.backStagePrice - b.backStagePrice}"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.backStagePrice }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="折扣率"
          sortable
          min-width="110"
          prop="profitRate"
          :sort-method="(a,b)=>{return a.profitRate - b.profitRate}"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.profitRate }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="京东SKU名称"
          min-width="200"
          prop="skuName"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span @click="">{{ scope.row.skuName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品图片" min-width="80" prop="imgUrl" align="center">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 40px; height: 40px"
                :src="scope.row.imgUrl?scope.row.imgUrl:moren"
                :preview-src-list="[scope.row.imgUrl]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="品牌名称"
          min-width="100"
          prop="brandName"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span @click="">{{ scope.row.brandName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="一级类目"
          min-width="120"
          prop="categoryName"
        >
          <template slot-scope="scope">
            <span @click="">{{ scope.row.categoryName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="二级类目"
          min-width="120"
          prop="categoryName1"
        >
          <template slot-scope="scope">
            <span @click="">{{ scope.row.categoryName1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="三级类目"
          min-width="120"
          prop="categoryName2"
        >
          <template slot-scope="scope">
            <span @click="">{{ scope.row.categoryName2 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="商品结构"
          min-width="100"
          prop="itemId"
        >
          <template slot-scope="scope">
            <span @click="">普通单品</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="是否全球购"
          min-width="100"
          prop="itemId"
        >
          <template slot-scope="scope">
            <span @click="">否</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="店铺模式"
          min-width="100"
          prop="itemId"
        >
          <template slot-scope="scope">
            <span @click="">自营</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="商品价格类型"
          min-width="100"
          prop="itemId"
        >
          <template slot-scope="scope">
            <span @click="">促销价</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="价格到期时间"
          min-width="100"
          prop="itemId"
        >
          <template slot-scope="scope">
            <span @click="">2023-12-31 23:59:59</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="isGather"
          label="是否采集"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isGather"
              :active-value="true"
              :inactive-value="false"
              active-text="已采"
              inactive-text="未采"
              inactive-color="#c8cad1"
              disabled
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="100" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="getProductInfo(scope.row.skuId,true)">详情</el-button>
            <el-button type="text" size="small" @click="onEdit(scope.row)" v-if="!scope.row.isGather">采集
            </el-button>
            <el-button type="text" size="small" v-else disabled>采集
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination :page-sizes="[20, 40, 60, 80]" :page-size="20"
                       ref="Pagination"
                       :current-page.sync="productFrom.page"
                       layout="total, sizes, prev, pager, next, jumper" :total="productData.total"
                       @size-change="handleSizeChange" @current-change="pageChange"/>
      </div>

    </el-card>
    <el-dialog title="商品详情" :visible.sync="dialogVisible" width="1000px" :before-close="handleClose"
               :append-to-body='append'>
      <div>
        <div class="item">
          <span style="font-size: 16px">商品名称：</span>
          <span style="font-size: 14px">{{ productDetail.skuBaseInfo.skuName }}</span>
        </div>

        <div class="item mt10">
          <span style="font-size: 16px">商品货号：</span>
          <span style="font-size: 14px">{{ productDetail.skuBaseInfo.productId }}</span>
        </div>

        <!--        <div class="item mt10">-->
        <!--          <span style="font-size: 16px">成交量：</span>-->
        <!--          <span style="font-size: 14px">{{ productDetail.skuBaseInfo.bookedCount }}</span>-->
        <!--        </div>-->
        <div class="item mt10">
          <span style="font-size: 16px">参考价格：</span>
          <span style="font-size: 14px">{{ productDetail.skuBaseInfo.isSuccess?productDetail.skuBaseInfo.skuPrice:productDetail.skuBaseInfo.errorMessage }}（元）</span>
        </div>
        <div class="item mt10">
          <span style="font-size: 16px">类目ID：</span>
          <span style="font-size: 14px">{{ productDetail.skuBaseInfo.categoryId }}</span>
        </div>
        <div class="item mt10">
          <span style="font-size: 16px">类目名：</span>
          <span style="font-size: 14px">{{ productDetail.skuBaseInfo.categoryName }}</span>
        </div>
        <div class="mt20" v-html="productDetail.skuBigFieldInfo.pcWdis"></div>
      </div>
    </el-dialog>
    <!--编辑标签-->
    <el-dialog
      v-if="dialogLabel"
      title="设置价格"
      :visible.sync="dialogLabel"
      width="800px"
      :before-close="handleClose"
    >
      <el-form :model="money" @submit.native.prevent>
        <el-form-item label="请设置价格：">
          <el-input v-model="money" placeholder="请输入价格" clearable
                    class="selWidth"/>
          <span style="font-size: 16px">（分）</span>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {
  storeCategoryCreateApi,
  storeCategoryDeleteApi,
  storeCategoryStatusApi,
  storeCategoryRecommendApi,
  productJdListApi,
  productJdGatherApi, productJdCateListApi, productJdProductInfoApi,
} from '@/api/product'
import {roterPre} from '@/settings'
import ueditorFrom from "@/components/ueditorFrom/index.vue";

export default {
  name: 'GatherAlibaba',
  components: {ueditorFrom},

  data() {

    return {
      isAlone: false,
      productFrom: {
        cate_ids: [],
        size: 20,
        cate_id: '',
        keyword: '',
        scroll_id: ''
      },
      isChange: false,//是否需要重置页码的开关
      money: '',
      append: true,
      dialogVisible: false,
      roterPre: roterPre,
      productInfo: {
        sku_id: ''
      },
      dialogLabel: false,
      productDetail: {
        skuBaseInfo: {},
        skuBigFieldInfo: {
          pcWdis: ''
        }
      },
      merCateList: [],
      value: [],
      multipleSelection: [],
      object: {sku_ids: []},
      sku_ids: [],
      productData: {},
      productList: [],
      moren: require("@/assets/images/bjt.png"),
      isChecked: false,
      listLoading: true,
      tableData: {
        data: [],
        total: 0
      },
      oldScrollId: '',
      images: [],
      // 商品多级分类
      cascaderProps: {
        emitPath: true,
        lazy: true, // 开启懒加载
        checkStrictly: false, //可选择任意节点
        lazyLoad: this.getCateList
      },
      pageInfo: {
        currentPage: 1
      },
      tableFrom: {
        page: 1,
        limit: 20
      },
      cateFrom: {
        cate_id: 0
      }

    }
  },
  mounted() {
    this.getProductJdListApi(true)
  },
  methods: {
    rowClass({row, rowIndex}) {
      return 'background:#F3F4F7;color:#555'
    },
    //jd商品列表
    getProductJdListApi(ischange) {
      this.listLoading = true
      if (this.productFrom.cate_ids.length > 0) {
        this.productFrom.cate_id = this.productFrom.cate_ids[this.productFrom.cate_ids.length - 1]
      }
      if (ischange) {
        this.productFrom.scroll_id = ''
      }
      console.log(this.productFrom)
      productJdListApi(this.productFrom).then(res => {
        this.productData = res.data
        this.productList = res.data.result
        this.productFrom.scroll_id = this.productData.scrollId
        this.listLoading = false
      }).catch(res => {
        this.listLoading = false
        //游标无效刷新页面
        if (res.data.status === 202) {
          this.getProductJdListApi(true)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //jd商品采集-批量
    productGather(rows) {
      this.listLoading = true
      console.log(this.object)
      productJdGatherApi(this.object).then(res => {
        this.listLoading = false
        this.$message.success(res.message)
        if (rows) {
          rows.forEach(row => {
            if (!row.isGather) {
              row.isGather = true
            }
          });
          this.$refs.multipleTable.clearSelection();
        }
        this.getProductJdListApi(false)
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    //jd商品采集-单独
    productGatherAlone(row) {
      this.listLoading = true
      this.object.sku_ids = []
      this.object.sku_ids.push(row.skuId)
      productJdGatherApi(this.object).then(res => {
        this.listLoading = false
        this.$message.success(res.message)
        this.getProductJdListApi(false)
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },
    //JD商品详情
    getProductInfo(sku_id, isShow) {
      this.listLoading = true
      this.productDetail = {}
      this.dialogVisible = isShow
      this.productInfo.sku_id = sku_id
      productJdProductInfoApi(this.productInfo).then(res => {
        this.productDetail = res.data
        this.listLoading = false
        console.log(this.productDetail.skuBigFieldInfo.pcWdis)
      }).catch(res => {
        this.listLoading = false
        this.$message.error(res.message)
      })
    },

    //JD商品类目列表
    getCateList(node, resolve) {
      const nodes = [];
      if (node.level <= 2 || node.root) {
        setTimeout(() => {
          // 构造查询条件
          let query = {
            cate_id: node.value,
            // level: node.level
          }
          //查询接口
          productJdCateListApi(query).then(res => {
            this.merCateList = res.data
            this.merCateList.map((item) => {
              let obj = {
                value: item.id,
                label: item.cate_name,
                leaf: node.level >= 2 // 节点级别，如果没有子节点就停止查询
              }
              nodes.push(obj);
            })
            //重新加载节点
            resolve(nodes);
          })
        }, 100);
      } else {
        //如果没有子节点就不发起请求，直接渲染，也避免了点击叶子节点仍然有加载动画的问题
        resolve(nodes);
      }

    },
    //重置
    reset(formName) {
      this.$refs[formName].resetFields();
      this.getProductJdListApi(true)
    },

    // 设置价格
    onEditMoney() {
      this.dialogLabel = true
    },
    //已采集的商品防止重复采集
    checkboxSelect(row) {
      if (row.isGather) {
        return false
      } else {
        return true
      }
    },
    submitForm() {
      console.log(this.money)
      this.dialogLabel = false
    },
    handleClose() {
      this.dialogVisible = false
      this.dialogLabel = false
    },
    pageChange() {
      this.getProductJdListApi(false)
    },
    handleSizeChange(val) {
      this.productFrom.size = val
      this.getProductJdListApi(true)
    },
    // 添加
    onAdd() {
      this.$modalForm(storeCategoryCreateApi()).then(() => this.getList())
    },
    // 采集
    onEdit(row) {
      this.productGatherAlone(row)
    },
    batch(rows) {
      if (this.multipleSelection.length === 0) {
        if (rows) {
          rows.forEach(row => {
            if (!row.isGather) {
              this.$refs.multipleTable.toggleRowSelection(row);
            }
          });
        }
      }
      this.modalSure(`确定采集这${this.multipleSelection.length}件商品吗`).then(() => {
          this.productGather(rows)
        }
      )

    },
    modalSure(title) {
      return new Promise((resolve, reject) => {
        this.$confirm(`${title || '删除该文件吗'}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resolve()
        }).catch(action => {
          this.$refs.multipleTable.clearSelection();
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      })
    },
    //单位换算 分-元
    getMoney(money) {
      let number = money / 100
      return number.toFixed(2);
    },
    // 删除
    handleDelete(id, idx) {
      this.$modalSure().then(() => {
        storeCategoryDeleteApi(id).then(({message}) => {
          this.$message.success(message)
          this.getList()
        }).catch(({message}) => {
          this.$message.error(message)
        })
      })
    },
    onchangeIsShow(row) {
      storeCategoryStatusApi(row.store_category_id, row.is_show).then(({message}) => {
        this.$message.success(message)
      }).catch(({message}) => {
        this.$message.error(message)
      })
    },
    onchangeIsRecommend(row) {
      storeCategoryRecommendApi(row.store_category_id, row.is_hot).then(({message}) => {
        this.$message.success(message)
      }).catch(({message}) => {
        this.$message.error(message)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      const data = []
      this.multipleSelection.map((item) => {
        data.push(item.skuId)
      })
      this.object.sku_ids = data
    },
  }
}
</script>

<style scoped lang="scss">
.item {
  display: flex;
  flex-direction: row;
}

.mt10 {
  margin-top: 10px;
}
</style>
